# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime

# requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告

"""
国家知识产权局-专利检索及分析
账号：testuser6666\6666testuser
http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiIndex.shtml
"""


class ZhuanLi():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        self.cookie = cookiejar.CookieJar()
        # ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Cookie": "WEE_SID=bEWqkDV9mU8HZbTDnibVuI1IJEWQn6amQ1l1Z1bBNHG-inXUJQtS!-1905825268!1311412577!1583409542525; IS_LOGIN=true; JSESSIONID=bEWqkDV9mU8HZbTDnibVuI1IJEWQn6amQ1l1Z1bBNHG-inXUJQtS!-1905825268!1311412577; DLjfPow8PDr480S=GVbGH2GTvKq_Ru.6FvrDogP6TBlZ7U1PZi6UEp5tbZLDH9DVP4xIvc303ITJI7e4pA35j9S6jSUrHBceq1Y1_A; DLjfPow8PDr480T=5VUR9HUK7QT2RVjKXS2_h9jQVJzL1MnME1SMvftQkfyr4FNckjNKE6V3VRdqxYVerUtmIJ.0N8..eg2JA8J5O4MypY19hQgSarM6BZ8N7aCjrAwGXFM9StrYnaRY0WLKJya9gunnx2pw7ISTYndNzzrKeskY7xDHlBDrewLRdZFOaJ3dVFVWGVl_iekOVmqlDZB.ngCmeDch2n.eKzw2BwD0leUaOy2BDij3fX7yUrOReXPU9M.js93DMbN6Vd.eb2067yD8.CuvLvhokK8gJXIrtoH1MlzzK_g1I.pGiIEESueTbz3.KFVviTntmSCLzwKdKPtpk7zc3B3U3kRm2V7.by81CYXFbUwNdk0PZN70q1Tw4v90Lm2XXBTCvTlHjyMg",
            "DNT": "1",
            "Host": "pss-system.cnipa.gov.cn",
            "Origin": "http://pss-system.cnipa.gov.cn",
            "Referer": "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiIndex.shtml",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest",
            # "User-Agent": ua.random,
        }

    def get_contents(self, pageNo):
        postData = {
            'resultPagination.limit':'12',
            'resultPagination.sumLimit':'10',
            'resultPagination.start':"12", # '12',
            'resultPagination.totalCount':'36489',
            'searchCondition.sortFields':'-APD,+PD',
            'searchCondition.searchType':'Sino_foreign',
            'searchCondition.originalLanguage':'',
            "searchCondition.extendInfo['MODE']":'MODE_SMART',
            "searchCondition.extendInfo['STRATEGY']":'',
            'searchCondition.searchExp':'复合文本=(大数据)',
            'searchCondition.executableSearchExp':"VDB:(TBI='大数据')",
            'searchCondition.dbId':'',
            'searchCondition.literatureSF':'复合文本=(大数据)',
            'searchCondition.targetLanguage':'',
            'searchCondition.resultMode':'SEARCH_MODE',
            'searchCondition.strategy':'',
            'searchCondition.searchKeywords':'[大][]{0,}[数][]{0,}[据][]{0,}'

        }
        url = "http://pss-system.cnipa.gov.cn/sipopublicsearch/patentsearch/showSearchResult-startWa.shtml"
        data = "7XzRcVlp=5WSADUSIils74WWIWNkuNZWYCYhfakV1jtU1my7YfyIERcHhfnHIjBnpCrRx.Jn0OH7WeYJehDJPIGklnD.6rOeauztl7r8pVDZ5O1robqnmtPEOs2fUrM.vRGmH3CMAUZTNoU7RNT1QbzlPYmNfrAHDVt4rgVuDy.mwX0uRYXfyKTToKwv4ZVAWv2i3AS9C8ZUHq1R60jgGPRDkLAGQaIytvYPbRu9APqciQYDb51P6yMy6aSKKgKxm9Dm4pEIhCZoplSrmImv3cUGgUNOeqrWmbqjdNmyE1gXEGiCoROTsIAELXzemcbKzRO0dtlFDYaxA83gDvqEU2BesUkjWldEgpw3.rdAUCULyM1n65RpagpxJxw73QznMoa3OTSumREzZYSDbQIdyl6gRHWeOp6PTAy.QbE4ujGcL8KTyaiJOkrzEqmmnScWiRSFZCZ5rqx_b"
        postData = "resultPagination.limit=12&resultPagination.sumLimit=10&resultPagination.start=12&resultPagination.totalCount=36489&searchCondition.sortFields=-APD%2C%2BPD&searchCondition.searchType=Sino_foreign&searchCondition.originalLanguage=&searchCondition.extendInfo%5B'MODE'%5D=MODE_SMART&searchCondition.extendInfo%5B'STRATEGY'%5D=&searchCondition.searchExp=%E5%A4%8D%E5%90%88%E6%96%87%E6%9C%AC%3D(%E5%A4%A7%E6%95%B0%E6%8D%AE)&searchCondition.executableSearchExp=VDB%3A(TBI%3D'%E5%A4%A7%E6%95%B0%E6%8D%AE')&searchCondition.dbId=&searchCondition.literatureSF=%E5%A4%8D%E5%90%88%E6%96%87%E6%9C%AC%3D(%E5%A4%A7%E6%95%B0%E6%8D%AE)&searchCondition.targetLanguage=&searchCondition.resultMode=SEARCH_MODE&searchCondition.strategy=&searchCondition.searchKeywords=%5B%E5%A4%A7%5D%5B+%5D%7B0%2C%7D%5B%E6%95%B0%5D%5B+%5D%7B0%2C%7D%5B%E6%8D%AE%5D%5B+%5D%7B0%2C%7D"
        html = requests.post(url, headers=self.headers, data=postData, params=data, verify=False)
        data_json = json.loads(html.text)
        for d in data_json['searchResultDTO']['searchResultRecord']:
            lawStatus = d['lawStatus']  # 公开类型： 公开、授权公告
            patentType = d['patentType']  # 专利类型：发明专利、实用新型
            TIVIEW = d['fieldMap']['TIVIEW']  # 简介
            AP = d['fieldMap']['AP']  # 申请号，法律
            APO = d['fieldMap']['APO']  # 申请号
            APD = d['fieldMap']['APD']  # 申请日
            PN = d['fieldMap']['PN']  # 公开（公告）号
            PD = d['fieldMap']['PD']  # 公开（公告）日
            IC = d['fieldMap']['IC']  # IPC分类号
            PAVIEW = d['fieldMap']['PAVIEW']  # 申请（专利权）人
            INVIEW = d['fieldMap']['INVIEW']  # 发明人
            AGT = d['fieldMap']['AGT']  # 代理人
            AGY = d['fieldMap']['AGY']  # 代理机构
            self.get_law(PN, AP)

    # 获取法律状态
    def get_law(self, Pn, An):
        postData = {
            "lawState.nrdPn": Pn,
            "lawState.nrdAn": An,
            "wee.bizlog.modulelevel": "0202201",
            "pagination.start": "0"
        }
        url = "http://pss-system.cnipa.gov.cn/sipopublicsearch/patentsearch/ui_searchLawState-showPage.shtml?7XzRcVlp=5ONCjou4r3bN5cdTt4p6xsmF7_uDVtYVHxJ8ydgicry5tgqVLsQkZls_RV52RRhyv13PgoFZtXnnkOuRdU53nwXE.pZuU35M2Gr1pXaRGtzhQXPxsq.QEYdKI.9OsV2UYQSUCGx2Q3NMwpoiMJR5KyEezn21aTfbaDNB072Z823c8qefH5CGUeWn7rnEJkTiy0DHlXHBUYyPyVktry3wEe_o85oSL0K7XYiDORsNmEuaty86McGHZAy6Q9bHcIbnvKQhM6koPbZ6IcKxeonATdcGPVlep42VeYqDpGB2bsMjrKKMnwmrKC9y2Xf11EHM.pkR02w44OQGrUhkX3xQX39_nUEoM1QX1G9atntmWq2uNWnaO__5oAYpbWKzXJC1.a3GYvxiVGxORO5pnaKh2s2ZkoKC_Eur5sSftEG7WR6HcDDEdyaH_xVG3iOo1Q_ZIdAt"
        html = HttpUtils.do_request("POST", url, self.headers, postData)
        data_json = json.loads(html.text)
        for d in data_json["lawStateList"]:
            nrdAn = d["nrdAn"]  # 申请号
            prsDate = d["prsDate"]  # 法律状态公告日
            lawStateCNMeaning = d["lawStateCNMeaning"]  # 法律状态含义


if __name__ == '__main__':
    zhuanli = ZhuanLi()
    for c in range(0, 2768, 12):
        zhuanli.get_contents(c)
    # zhuanli.get_law("CN110601994A", "CN201910973419")
